package ru.vsu.cs.kis.elections.socketexchenge.commands;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;

import ru.vsu.cs.kis.elections.dto.PrecinctDto;
import ru.vsu.cs.kis.elections.parser.ObjStreamParser;
import ru.vsu.cs.kis.elections.server.dao.PrecinctDao;
import ru.vsu.cs.kis.elections.server.db.DBConnector;

public class SendPrecinctCommand extends Command {

	private PrecinctDto dto;
	
	public SendPrecinctCommand(Socket socket) {
		super(socket);		
	}

	public SendPrecinctCommand(Socket socket,PrecinctDto dto) {
		super(socket);
		this.dto = dto;
	}

	@Override
	public Integer executeOnClient() {
		Integer result=-1;
		try {			
			BufferedOutputStream aOutStr = new BufferedOutputStream(
					socket.getOutputStream());
			BufferedInputStream aInStr=new BufferedInputStream(socket.getInputStream());
			aOutStr.write(CommandsNumber.SEND_PRECINCT);
			aOutStr.flush();
			ObjStreamParser.parseToStream(dto, aOutStr);
			aOutStr.flush();			
			result=aInStr.read();
			aInStr.close();	
			aOutStr.close();
			
			if (result >= 0) {
				System.out.println("PrecinctDTO write success ");
			}
			else{
				System.out.println("DTO write crash ");
			}	
		} catch (IOException Ex) {
			Ex.printStackTrace(System.err);
			return(result);
		}
		return(result);		
	}
	
	@Override
	public Integer executeOnServer() {		
		Integer result=-1;
		try {	
			BufferedOutputStream aOutStr = new BufferedOutputStream(
					socket.getOutputStream());
			BufferedInputStream aInStr=new BufferedInputStream(socket.getInputStream());
			dto=(PrecinctDto)ObjStreamParser.parseToDTO(aInStr);
			
			
			PrecinctDao prDao = DBConnector.getPrecinctDao();
			prDao.checkOrRegistr(dto);
			prDao.checkPW(dto.getAddress(), dto.getPassword());
			prDao.vote(dto);
			
			aOutStr.write(0);
			aOutStr.flush();
			result=0;
		} catch (IOException Ex) {
			Ex.printStackTrace(System.err);
			return(result);
		}
		return(result);		
	}
}
